<?php
namespace Admin\Controller;
use Common\Controller\AdminbaseController;
use Admin\Controller\Tencentyun\Conf;
use Admin\Controller\Tencentyun\ImageV2;
use Think\Page;
use Common\Model\NewPage;
use Common\Model\AjaxPage;
use Common\Model\NewsColumnTypeModel;
use Common\Model\ImageProcess;

class ResourcesController extends AdminbaseController{
	protected $resources_library_model;
	protected $admin_id;
	private $video_type    = 4;
	private $vr_video_type = 5;
	private $text          = 6;
	private $image_text    = 7;
	
	function _initialize() {
		parent::_initialize();
		$this->resources_library_model = D("Common/ResourceLibrary");
		$this->live = D("Common/Live");
		$this->admin_id = $_SESSION['ADMIN_ID'];
	}
	
	
	//全部列表
	function index(){
		$this->display();
	}

	//视频列表
	function video_index(){
		$formParam['Name'] = I('param.Name', '');
		$formParam['creatorName'] = I('param.creatorName', '');
		$formParam['startDate'] = I('param.startDate', '');
		$formParam['endDate'] = I('param.endDate', '');
		$formParam['Type'] = '1';
		$this->assign("formParam", $formParam);
	
		$currentPage = I('param.p', 0);
		if ($currentPage <= 0) {
			$currentPage = 1;
		}
	
		$pageSize = '20';
		$pageStart = ($currentPage - 1) * $pageSize;
		$pageEnd = $currentPage * $pageSize;
		$result = $this->live_resources_model->getResourcesList($formParam,$pageStart,$pageSize);
	
	
		$this->assign("data", $result['data']);
		$this->assign("type", $this->self_admin_model['type']);
	
		//分页
		$page = $this->page($result['count_Total'], 20);
		$this->assign("page", $page->show('Admin'));

		$this->assign("data", $result['data']);
		$this->display();
	}
	
	
	//外链列表
	function outside_index(){
		$formParam['Name'] = I('param.Name', '');
		$formParam['creatorName'] = I('param.creatorName', '');
		$formParam['startDate'] = I('param.startDate', '');
		$formParam['endDate'] = I('param.endDate', '');
		$formParam['Type'] = '2';
		$this->assign("formParam", $formParam);
		
		$currentPage = I('param.p', 0);
		if ($currentPage <= 0) {
			$currentPage = 1;
		}
		
		$pageSize = '20';
		$pageStart = ($currentPage - 1) * $pageSize;
		$pageEnd = $currentPage * $pageSize;
		$result = $this->live_resources_model->getResourcesList($formParam,$pageStart,$pageSize);
		
		
		$this->assign("data", $result['data']);
		$this->assign("type", $this->self_admin_model['type']);
		
		//分页
		$page = $this->page($result['count_Total'], 20);
		$this->assign("page", $page->show('Admin'));
		
		$this->assign("data", $result['data']);
		$this->display();
	}
	
	
	/**
	 * 业务
	 */
	function del()
	{
		$resource_id = I('param.resource_id', "");
		if (empty($resource_id)) {
			$this->error("参数错误！");
		}
		$result = $this->live_resources_model->resourcesDel($resource_id);
		if ($result !==false) {
			$this->success("删除成功！");
		} else {
			return $this->error($result['Message']);
		}
	}
	
	
	
	/**
	 * 进入添加外链页面
	 */
	function outsideAdd()
	{
		$resource_id = I('param.resource_id', "");
		$resource_info = array();
		
		if(!empty($resource_id)){
			$resource_info = $this->live_resources_model->find($resource_id);
			$this->assign("Title", "修改外链");
		}else{
			$this->assign("Title", "添加外链");
		}
		
		$this->assign('resource_data',$resource_info);
		$this->display('outsideadd');
	}
	
	
	
	/**
	 * 外链提交
	 */
	function outsideAddPost()
	{
		$resource_id =  I("param.resource_id", "");
		$name =  I("param.name", "");
		$introduction =  I("param.introduction", "");
		$link_url =  I("param.link_url", "");
		
		
		if (empty($name)) {
			$this->error("外链名称不能为空！");
		}else{
			if(mb_strlen(trim($name),'UTF8') > 20){
				$this->error("字数超过20字限制！");
			}
		}
		if($introduction){
			if(mb_strlen(trim($introduction),'UTF8') > 120){
				$this->error("字数超过120字限制！");
			}
		}
		if (empty($link_url)) {
			$this->error("外链地址不能为空！");
		}
		
		$data['name'] = $name;
		$data['introduction'] = $introduction;
		$data['link_url'] = $link_url;
		$data['creator_id'] = $this->admin_id;
		$data['status'] = '1';
		$data['type'] = '2';
		
		if(empty($resource_id)){
			$data['create_time'] = date('Y-m-d H:i:s',time());
			$rid = $this->live_resources_model->add($data);
			$successInfo = "添加成功";
		}else{
			$data['update_time'] = date('Y-m-d H:i:s',time());
			$rid = $this->live_resources_model->where('resource_id = '.$resource_id)->data($data)->save();
			$successInfo = "编辑成功";
		}

		if($rid){
			$this->success($successInfo, U("Admin/Resources/outside_index"));
		}else{
			$this->error($result['Message']);
		}
	}
	
	/**
	 *----------------------------------------------------------列表部分-------------------------------------------------------
	 */
	
	
	/**
	 * 资源池列表
	 * @cong.zhao
	 */
	function resource_library($show_type='1', $is_ajax = false){
		
		$_GET = I();
		$admin_id = $_SESSION['ADMIN_ID'];
		$formParam['operation_id'] = $admin_id;
		$formParam['Name'] = I('param.Name', '');
		//$formParam['creatorName'] = I('param.creatorName', '');
		$formParam['startDate'] = I('param.startDate', '');
		$formParam['endDate'] = I('param.endDate', '');
		$formParam['type'] = I('param.type', '1');
		$formParam['is_water'] = I('param.is_water', '');
		$formParam['order'] = I('param.order', 'desc');
		$this->assign("formParam", $formParam);

		$show_type = I("param.show_type",'1'); 
		$set_water = I("param.set_water",'0');
		$chosed_resource_ids = I("param.chosed_resource_ids",'');
		$before_type = I("param.before_type");
		$call_back = I("param.call_back");
		$transcoding_videos_name = I("param.transcoding_videos_name",'');

		$this->assign("show_type", $show_type);
		$this->assign("set_water", $set_water);
		$this->assign("before_type", $before_type);
		$this->assign("call_back", $call_back);
		$this->assign("transcoding_videos_name", $transcoding_videos_name);
		$this->assign('chosed_resource_ids', $chosed_resource_ids);
		$this->assign('chosed_resource_ids_arr', explode(',', $chosed_resource_ids));
		
		$currentPage = I('param.p', 0);
		if ($currentPage <= 0) {
			$currentPage = 1;
		}
		
		$pageSize = '5';
		$pageStart = ($currentPage - 1) * $pageSize;
		$pageEnd = $currentPage * $pageSize;
		$result = $this->resources_library_model->getResourcesList($show_type,$formParam,$pageStart,$pageSize);
		
// 		$this->assign("all_data", $result['all_data']);
		$this->assign("data", $result['data']);
		$this->assign("type", $this->self_admin_model['type']);
		//分页
		
		if($show_type == '1'){
			$page = $this->page($result['count_Total'], $pageSize);
			$this->assign("page", $page->show('Admin'));
		}else{
			$page = new AjaxPage($result['count_Total'], $pageSize, 'show');
			$this->assign("page", $page->show());
		}
// 		$page = $this->page($result['count_Total'], $pageSize);
// 		$this->assign("page", $page->show('Admin'));

		if($is_ajax){
			$this->display('ajax_resource_library');
		}else{
			$this->display();
		}	
	}
	
	
	/**
	 * 媒体库列表(新闻)
	 * @cong.zhao
	 */
	function resource_library_news($is_ajax = false){
		$formParam['newsTitle'] = I('param.newsTitle') ? I('param.newsTitle') : "";
		$chosed_resource_ids = I("param.chosed_resource_ids",'');
		$call_back = I("param.call_back");
		
		$and_newstitle = '';
		if(!empty(I('param.newsTitle'))){
			$and_newstitle = " and title like '%".I('param.newsTitle')."%'";
			$formParam['newsTitle'] = I('param.newsTitle');
		}else{
			$formParam['newsTitle'] = "";
		}
		
		//搜索 栏目
		$news_type = (int)I('news_type');
		if($news_type && $news_type > 1){
			$and_type = ' AND vrnews1.news.type='.$news_type.' ';
			if($news_type == $this->video_type){
				//普通视频
				$and_type = ' AND vrnews1.news.type=4 AND vrnews1.news_video.category=1';
			}elseif($news_type == 6){
				//VR视频
				$and_type = ' AND vrnews1.news.type=5';
			}
			elseif($news_type == $this->vr_video_type){
				//VR视频
				$and_type = ' AND vrnews1.news.type=4 AND vrnews1.news_video.category=2';
			}elseif($news_type == 7){
				$and_type = " AND vrnews1.news.type=$this->text ";
			}elseif($news_type == 8){
				$and_type = " AND vrnews1.news.type=$this->image_text ";
			}
			 
		}
		
		$currentPage = I('param.p', 0);
		if ($currentPage <= 0) {
			$currentPage = 1;
		}
		
		$pageSize = '10';
		$pageStart = ($currentPage - 1) * $pageSize;
		$pageEnd = $currentPage * $pageSize;
		$news = M("vrnews1.news", NULL);

		//查询出所有数据,为了在ajax分页的时候操作删除不报参数缺失
// 		$all_data = $news->where("special_news_id = 0 and  vrnews1.news.type !=2" .$and_newstitle . $and_type)
// 		->join("vrnews1.news_video on news.news_id = news_video.news_id",'left')
// 		->field("vrnews1.news.title,vrnews1.news.news_id,vrnews1.news.type")
// 		->select();

		
		$list = $news->where("special_news_id = 0 and  vrnews1.news.type !=2" .$and_newstitle . $and_type)
		->join("vradmin1.admin_user on admin_user.admin_id = vrnews1.news.creator_id", 'left')
		->join("vrnews1.news_video on news.news_id = news_video.news_id",'left')
		->field("vrnews1.news.*,vrnews1.news_video.status as video_status, vrnews1.news_video.category as video_category, vradmin1.admin_user.username,year(vrnews1.news.create_time) as year1,month(vrnews1.news.create_time) as month1,day(vrnews1.news.create_time) as day1,year(from_unixtime(refresh_time)) as year,month(from_unixtime(refresh_time)) as month,day(from_unixtime(refresh_time)) as day,from_unixtime(refresh_time) as refresh_time")
		->Order("
            		top_status desc,
            		case  when year is null then year1 else year end desc,
            		case  when month is null then month1 else month end desc,
            		case  when day is null then day1 else day end desc,
            		weight desc,
            		refresh_time desc,
            		create_time desc")
		 ->limit($pageStart,$pageSize)->select();
		$count = $news->where("special_news_id = 0 and  vrnews1.news.type !=2" .$and_newstitle . $and_type)
		->join("vradmin1.admin_user on admin_user.admin_id = vrnews1.news.creator_id", 'left')
		->join("vrnews1.news_video on vrnews1.news_video.news_id = vrnews1.news.news_id", 'left')
		->count();
		if(!empty($carousel_figure_list)){
			foreach($carousel_figure_list as $key=>&$val){
				$str = '';
				if($val['web_pub'] == 1){
					$str .= '门户网站, ';
				}
				if($val['app_pub'] == 1){
					$str .= 'APP';
				}
				$carousel_figure_list[$key]['pub'] = rtrim($str, ',');
		
				$val['type_zh'] = $this->_getNewType($val);
			}
			unset($val);
		}
		
		if(!empty($list)){
			foreach($list as $key=>&$val){
				$str = '';
				if($val['web_pub'] == 1){
					$str .= '门户网站, ';
				}
				if($val['app_pub'] == 1){
					$str .= 'APP';
				}
				$list[$key]['pub'] = rtrim($str, ',');
		
				/* 显示类型 */
				$val['type_zh'] = $this->_getNewType($val);
		
				/* 如果是引用的视频显示转码成功 */
				if($val['reference_id'] && $val['reference_type'] == 1){
					$val['video_status'] = 2;
				}
			}
			unset($val);
		}
		
		$this->assign("carousel_figure_data", $carousel_figure_list);
		$this->assign("all_data", $all_data);
		$this->assign("data", $list);
		//分页
		$page = new AjaxPage($count, $pageSize, 'show');
		$this->assign("page", $page->show());
		//1 快捷发布 2 轮播图 3 专题 4 视频 5 图集 6文本 7图文
		$type_list = [
				['id'=>1, 'name'=>'全部'],
				//['id'=>2, 'name'=>'轮播图 '],
				['id'=>3, 'name'=>'专题'],
				['id'=>4, 'name'=>'普通视频'],
				['id'=>5, 'name'=>'VR视频'],
				['id'=>6, 'name'=>'图集'],
				['id'=>7, 'name'=>'文本'],
				['id'=>8, 'name'=>'图文'],
				['id'=>9, 'name'=>'视频直播'],
				['id'=>10, 'name'=>'VR直播'],
				['id'=>11, 'name'=>'图文直播'],
				['id'=>12, 'name'=>'视频加图文直播'],
				['id'=>13, 'name'=>'VR加图文直播']
		];
		
		$this->assign('call_back', $call_back);
		$this->assign('type_list', $type_list);
		$this->assign('select_type', $news_type);
		$this->assign('live_open',$live_open);
		$this->assign('live_role',$live_role);
		$this->assign('formParam',$formParam);
		$this->assign('chosed_resource_ids',$chosed_resource_ids);
		$this->assign('chosed_resource_ids_arr', explode(',', $chosed_resource_ids));
		
		if($is_ajax){
			$this->display('ajax_resource_library_news');
		}else{
			$this->display();
		}
	}
	
	/**
	 * 媒体库列表(直播)
	 * @cong.zhao
	 */
	function resource_library_live($is_ajax = false){
		$_GET = I();
		$status = I("param.status", -1);
		$category = I("param.category", -1);
		$name = I("param.name", "");
		$chosed_resource_ids = I("param.chosed_resource_ids",'');
		$call_back = I("param.call_back");
		
		$currentPage = I('param.p', 0);
		if ($currentPage <= 0) {
			$currentPage = 1;
		}
		
		$pageSize = '10';
		$pageStart = ($currentPage - 1) * $pageSize;
		$pageEnd = $currentPage * $pageSize;
		
		$count = $this->live->queryLiveCount($status, $name, $category);
		$result = $this->live->queryLiveList($status, $name, $category, $pageStart,$pageSize); //获取直播列表
		
		//分页
		$page = new AjaxPage($count, $pageSize, 'show');
		
		if($result && !empty($result)){
			foreach($result as $key=>&$value){
				$start_time = strtotime($value['start_time']);
				$status1 = $value['status'];
				if($start_time > time()){  //开始时间大于当前时间：未开始
					$value['status'] = 3;
				}else if(2 == $status1 || 5 == $status1){ //已结束
					$value['status'] = $status1;
					if($value['red_score'] && !empty($value['red_score'])){  //结果已公布，返回红方蓝方的信息
						$red_competitor_id = $value["red_competitor_id"];
						$blue_competitor_id = $value["blue_competitor_id"];
						$red = $this->live_competitor->find($red_competitor_id);
						$blue = $this->live_competitor->find($blue_competitor_id);
						$value['red_competitor'] = $red['real_name'];
						$value['blue_competitor'] = $blue['real_name'];
					}
				}else{ //直播中
					$value['status'] = 4;
				}
			}
		}
		
		
		$this->assign("call_back", $call_back);
		$this->assign("page", $page->show());
		$this->assign("data", $result);
		$this->assign("formParam", array('status'=>$status,'name'=>$name,'category'=>$category));
		$this->assign('chosed_resource_ids',$chosed_resource_ids);
		$this->assign('chosed_resource_ids_arr', explode(',', $chosed_resource_ids));
		if($is_ajax){
			$this->display('ajax_resource_library_live');
		}else{
			$this->display();
		}
	}
	
	
	
	/**
	 *----------------------------------------------------------分页部分------------------------------------------------------- 
	 */
	
	/**
	 * 分页插件重新加载资源池列表
	 * @cong.zhao
	 */
	function get_page(){
		$_GET = I();
		$admin_id = $_SESSION['ADMIN_ID'];
		$formParam['operation_id'] = $admin_id;
		$formParam['Name'] = I('param.Name', '');
		//$formParam['creatorName'] = I('param.creatorName', '');
		$formParam['startDate'] = I('param.startDate', '');
		$formParam['endDate'] = I('param.endDate', '');
		$formParam['type'] = I('param.type', '1');
		$formParam['is_water'] = I('param.is_water', '');
		$formParam['order'] = I('param.order', 'desc');
		$this->assign("formParam", $formParam);

		$show_type = I("param.show_type",'1');
		$chosed_resource_ids = I("param.chosed_resource_ids",'');

		$this->assign("show_type", $show_type);
		$this->assign('chosed_resource_ids', $chosed_resource_ids);
		$this->assign('chosed_resource_ids_arr', explode(',', $chosed_resource_ids));
	
		$currentPage = I('param.p', 0);
		if ($currentPage <= 0) {
			$currentPage = 1;
		}
	
		$pageSize = '5';
		$pageStart = ($currentPage - 1) * $pageSize;
		$pageEnd = $currentPage * $pageSize;
		$result = $this->resources_library_model->getResourcesList($show_type,$formParam,$pageStart,$pageSize);
	
		$this->assign("data", $result['data']);
		$this->assign("type", $this->self_admin_model['type']);
		$page = new AjaxPage($result['count_Total'], $pageSize, 'show');
	
		echo $page->show();exit;
	}
	
	/**
	 * 分页插件重新加载资料库列表
	 * @cong.zhao
	 */
	function get_page_news(){
		$_GET = I();
		$formParam['newsTitle'] = I('param.newsTitle', '');
		$formParam['news_type'] = I('param.news_type', '');
		$this->assign("formParam", $formParam);
		$chosed_resource_ids = I("param.chosed_resource_ids",'');
		
		$and_newstitle = '';
		if(!empty(I('param.newsTitle'))){
			$and_newstitle = " and title like '%".I('param.newsTitle')."%'";
			$formParam['newsTitle'] = I('param.newsTitle');
		}else{
			$formParam['newsTitle'] = "";
		}
		
		//搜索 栏目
		$news_type = (int)I('news_type');
		if($news_type && $news_type > 1){
			$and_type = ' AND vrnews1.news.type='.$news_type.' ';
			if($news_type == $this->video_type){
				//普通视频
				$and_type = ' AND vrnews1.news.type=4 AND vrnews1.news_video.category=1';
			}elseif($news_type == 6){
				//VR视频
				$and_type = ' AND vrnews1.news.type=5';
			}
			elseif($news_type == $this->vr_video_type){
				//VR视频
				$and_type = ' AND vrnews1.news.type=4 AND vrnews1.news_video.category=2';
			}elseif($news_type == 7){
				$and_type = " AND vrnews1.news.type=$this->text ";
			}elseif($news_type == 8){
				$and_type = " AND vrnews1.news.type=$this->image_text ";
			}
			 
		}
		
		$currentPage = I('param.p', 0);
		if ($currentPage <= 0) {
			$currentPage = 1;
		}
		
		$pageSize = '10';
		$pageStart = ($currentPage - 1) * $pageSize;
		$pageEnd = $currentPage * $pageSize;
		$news = M("vrnews1.news", NULL);
		
		$count = $news->where("special_news_id = 0 and  vrnews1.news.type !=2" .$and_newstitle . $and_type)
		->join("vradmin1.admin_user on admin_user.admin_id = vrnews1.news.creator_id", 'left')
		->join("vrnews1.news_video on vrnews1.news_video.news_id = vrnews1.news.news_id", 'left')
		->count();
		
		$this->assign('chosed_resource_ids', $chosed_resource_ids);
		$this->assign('chosed_resource_ids_arr', explode(',', $chosed_resource_ids));
		
		//分页
		$page = new AjaxPage($count, $pageSize, 'show');
		echo $page->show();exit;
	}
	
	/**
	 * 分页插件重新加载资料库列表(直播)
	 * @cong.zhao
	 */
	function get_page_live(){
		$_GET = I();
		$status = I("param.status", -1);
		$category = I("param.category", -1);
		$name = I("param.name", "");
		$chosed_resource_ids = I("param.chosed_resource_ids",'');
		
		$currentPage = I('param.p', 0);
		if ($currentPage <= 0) {
			$currentPage = 1;
		}
		
		$pageSize = '10';
		$pageStart = ($currentPage - 1) * $pageSize;
		$pageEnd = $currentPage * $pageSize;
		
		$count = $this->live->queryLiveCount($status, $name, $category);
		
		$this->assign("formParam", array('status'=>$status,'name'=>$name,'category'=>$category));
		$this->assign('chosed_resource_ids', $chosed_resource_ids);
		$this->assign('chosed_resource_ids_arr', explode(',', $chosed_resource_ids));
	
		//分页
		$page = new AjaxPage($count, $pageSize, 'show');
		echo $page->show();exit;
	}
	
	
	/**
	 * 打开添加资源层
	 * @cong.zhao
	 */
	function add_resource(){
		$time = time();
		$type = I("param.type",'');   //添加类型
		$call_back = I("param.call_back",'');   //回调方法
		$show_type = I("param.show_type",'1');
		$set_water = I("param.set_water",'0');
		$chosed_resource_ids = I("param.chosed_resource_ids",'');
		$this->assign("show_type", $show_type);
		$this->assign("set_water", $set_water);
		$this->assign('chosed_resource_ids', $chosed_resource_ids);
		$this->assign('chosed_resource_ids_arr', explode(',', $chosed_resource_ids));
		$this->assign('time', $time);
		$this->assign('type', $type);
		$this->assign('call_back', $call_back);
		$this->display();
	}
	
	
	
	/**
	 * 分片上传文件
	 * @return string|unknown|boolean
	 */
	public function upload_files(){
		$REQUEST_METHOD=$_SERVER['REQUEST_METHOD'];
		global $uploads_dir;
	
		$fileDir = $_REQUEST['resumableFileDir'];
		$uploads_dir="data/upload/resource_upload";
		if($REQUEST_METHOD == "GET")
		{
			if(count($_GET)>0)
			{
				$chunkNumber = $_GET['resumableChunkNumber'];
				$chunkSize = $_GET['resumableChunkSize'];
				$totalSize = $_GET['resumableTotalSize'];
				$identifier = $_GET['resumableIdentifier'];
				$filename = iconv ( 'UTF-8', 'GB2312', $_GET ['resumableFilename'] );
				$time = $_GET['resumableTime'];
				$set_water = $_GET['resumableFileSetWater'];
				if($this->validateRequest($chunkNumber, $chunkSize, $totalSize, $identifier, $filename)=='valid')
				{
					$chunkFilename = $this->getChunkFilename($chunkNumber, $identifier,$filename);
					{
						if(file_exists($chunkFilename)){
							echo "found";
						} else {
							header("HTTP/1.0 404 Not Found");
							echo "not_found";
						}
					}
				}
				else
				{
					header("HTTP/1.0 404 Not Found");
					echo "not_found";
				}}
		}
	
		if($REQUEST_METHOD == "POST"){
			if(count($_POST)>0)
			{
				$time = $_POST['resumableTime'];
				$resumableFilename = iconv ( 'UTF-8', 'GB2312', $_POST ['resumableFilename'] );//$_POST ['resumableFilename'];//
				$tmpFilename = $resumableFilename;//'test'.$time.'.'.strtolower(substr(strrchr($resumableFilename,"."),1));
				$resumableIdentifier=$_POST['resumableIdentifier'];
				$resumableChunkNumber=$_POST['resumableChunkNumber'];
				$resumableTotalSize=$_POST['resumableTotalSize'];
				$resumableChunkSize=$_POST['resumableChunkSize'];
				$resumableSetWater = $_POST['resumableFileSetWater'];
				if (!empty($_FILES)) foreach ($_FILES as $file) {
					// check the error status
					if ($file['error'] != 0) {
						$this->_log('error '.$file['error'].' in file '.$tmpFilename);
						continue;
					}
					// init the destination file (format <filename.ext>.part<#chunk>
					// the file is stored in a temporary directory
					 
					global $uploads_dir;
	
					$temp_dir = $uploads_dir.'/'.$resumableIdentifier;
					$dest_file = $temp_dir.'/'.$tmpFilename.'.part'.$resumableChunkNumber;
					// create the temporary directory
					if (!is_dir($temp_dir)) {
						mkdir($temp_dir, 0777, true);
					}
					// move the temporary file
					if (!move_uploaded_file($file['tmp_name'], $dest_file)) {
						$this->_log('Error saving (move_uploaded_file) chunk '.$resumableChunkNumber.' for file '.$tmpFilename);
					} else {
						// check if all the parts present, and create the final destination file
						$this->createFileFromChunks($temp_dir, $resumableFilename, $tmpFilename, $resumableChunkSize, $resumableTotalSize, $resumableSetWater);
					}
				}
			}
		}
	}
	
	
	function cleanIdentifier ($identifier){
		return $identifier;
	}
	
	
	function validateRequest ($chunkNumber, $chunkSize, $totalSize, $identifier, $filename, $fileSize=''){
		// Clean up the identifier
		//$identifier = cleanIdentifier($identifier);
		// Check if the request is sane
		if ($chunkNumber==0 || $chunkSize==0 || $totalSize==0 || $identifier==0 || $filename=="") {
			return 'non_resumable_request';
		}
		$numberOfChunks = max(floor($totalSize/($chunkSize*1.0)), 1);
		if ($chunkNumber>$numberOfChunks) {
			return 'invalid_resumable_request1';
		}
		// Is the file too big?
		//      if($maxFileSize && $totalSize>$maxFileSize) {
		//          return 'invalid_resumable_request2';
		//      }
		if($fileSize!="") {
			if($chunkNumber<$numberOfChunks && $fileSize!=$chunkSize) {
				// The chunk in the POST request isn't the correct size
				return 'invalid_resumable_request3';
			}
			if($numberOfChunks>1 && $chunkNumber==$numberOfChunks && $fileSize!=(($totalSize%$chunkSize)+$chunkSize)) {
				// The chunks in the POST is the last one, and the fil is not the correct size
				return 'invalid_resumable_request4';
			}
			if($numberOfChunks==1 && $fileSize!=$totalSize) {
				// The file is only a single chunk, and the data size does not fit
				return 'invalid_resumable_request5';
			}
		}
		return 'valid';
	}
	
	
	/**
	 *
	 * Logging operation - to a file (upload_log.txt) and to the stdout
	 * @param string $str - the logging string
	 */
	function _log($str) {
		// log to the output
		$log_str = date('d.m.Y').": {$str}\r\n";
		echo $log_str;
		// log to file
		if (($fp = fopen('upload_log.txt', 'a+')) !== false) {
			fputs($fp, $log_str);
			fclose($fp);
		}
	}
	
	
	/**
	 *
	 * Delete a directory RECURSIVELY
	 * @param string $dir - directory path
	 * @link http://php.net/manual/en/function.rmdir.php
	 */
	function rrmdir($dir) {
		if (is_dir($dir)) {
			$objects = scandir($dir);
			foreach ($objects as $object) {
				if ($object != "." && $object != "..") {
					if (filetype($dir . "/" . $object) == "dir") {
						$this->rrmdir($dir . "/" . $object);
					} else {
						unlink($dir . "/" . $object);
					}
				}
			}
			reset($objects);
			rmdir($dir);
		}
		return true;
	}
	
	/**
	 *
	 * Check if all the parts exist, and
	 * gather all the parts of the file together
	 * @param string $dir - the temporary directory holding all the parts of the file
	 * @param string $fileName - the original file name
	 * @param string $chunkSize - each chunk size (in bytes)
	 * @param string $totalSize - original file size (in bytes)
	 */
	function createFileFromChunks($temp_dir, $fileName, $tmpFileName, $chunkSize, $totalSize, $resumableSetWater) {
		// count all the parts of this file
		$total_files = 0;
		foreach(scandir($temp_dir) as $file) {
			if (stripos($file, $tmpFileName) !== false) {
				$total_files++;
			}
		}
		// check that all the parts are present
		// the size of the last part is between chunkSize and 2*$chunkSize
		if ($total_files * $chunkSize >=  ($totalSize - $chunkSize + 1)) {
			global $uploads_dir;
			// create the final destination file
			if (($fp = fopen($uploads_dir.'/'.$tmpFileName, 'w')) !== false) {
				for ($i=1; $i<=$total_files; $i++) {
					fwrite($fp, file_get_contents($temp_dir.'/'.$tmpFileName.'.part'.$i));
					//_log('writing chunk '.$i);
				}
				fclose($fp);
			} else {
				$this->_log('cannot create the destination file');
				return false;
			}
			// rename the temporary directory (to avoid access from other
			// concurrent chunks uploads) and than delete it
			if (rename($temp_dir, $temp_dir.'_UNUSED')) {
				$this->rrmdir($temp_dir.'_UNUSED');
			} else {
				$this->rrmdir($temp_dir);
			}

			//echo $totalSize."~".basename($fileName);
			//$fileName_arr = explode('.', $fileName);
			//echo $totalSize."~".iconv('GB2312', 'UTF-8', $fileName_arr[0]).'.'.$fileName_arr[1];exit; //将字符串的编码从GB2312转到UTF-8
			
			//资源表创建数据
			$resource_model = M("vrnews1.resource_library", NULL);
			$data = array();
			$data['resource_id'] = time().$this->getRange();
			
			//$fileName = iconv('GB2312', 'UTF-8', $fileName);
			$fileEx=strtolower(substr(strrchr($tmpFileName,"."),1));
			if(in_array($fileEx,  array('jpeg', 'jpg', 'bmp', 'png','gif'))){ //上传图片
				$cname = $uploads_dir.'/'.$tmpFileName;
				$newFileName = 'lv'.time().$tmpFileName;  // 自定义文件名s
// 				echo $resumableSetWater;exit;
				if($resumableSetWater == '1' && $fileEx !='gif'){
					$logo = 'logo.png';
					//根据比例缩放水印图
					$ginfo = getimagesize($cname);
					$base = $ginfo[0] > $ginfo[1] ? $ginfo[0] : $ginfo[1];
					$proportion = round($base/800,1);
					$logo_process = new ImageProcess($logo);
					$new_logo = $logo_process->scaleImage($proportion,$logo,"data/upload/resource_upload/new_logo.png");

					$image_process = new ImageProcess($cname);
					$new_pic = $image_process->watermarkImage($new_logo);
					$uploadRet = ImageV2::upload($new_pic, Conf::BUCKET, $newFileName);
				}else{
					$uploadRet = ImageV2::upload($cname, Conf::BUCKET, $newFileName);
				}

				//删除本地文件
				unlink($cname);
				if($uploadRet['httpcode'] == 200){
					$imageUrl = $uploadRet['data']['downloadUrl'];
					
					$data['thumbnail_url'] = $imageUrl;
					$data['file_name'] = iconv('GB2312', 'UTF-8', $fileName);
					$data['type'] = '1';
					$data['create_time'] = date('Y-m-d H:i:s',time());
					if($resumableSetWater == '1') $data['is_water'] = '1';
					$data['operation_id'] = $_SESSION['ADMIN_ID'];
					if($resource_model->add($data)){
						if($resumableSetWater == '1'){
							unlink($new_logo);
							unlink($new_pic);
						}
						echo '1~'.$data['resource_id'].'~'.iconv('GB2312', 'UTF-8', $fileName).'~'.$imageUrl;exit;
						//return $resource_model->resource_id;
						//return true;
					}
				}
			}elseif(in_array($fileEx,  array('avi', 'mp4', 'rmvb', 'flv', 'asf', 'rm', '3gp', 'wmv', 'mpeg', 'mpg','mov'))){ //上传视频
					$savename = $uploads_dir.'/'.$fileName;
// 					$handle=fopen($savename,"r");//使用打开模式为r
// 					$content=fread($handle,filesize($savename));//读为二进制
// 					$config = array('SecretId'       => C("API_SecretId"),
// 							'SecretKey'      => C("API_SecretKey"),
// 							'RequestMethod'  => 'POST',
// 							'DefaultRegion'  => C("API_DefaultRegion"));
// 					vendor("QcloudApi.QcloudApi");
// 					$service = \QcloudApi::load(\QcloudApi::MODULE_VOD, $config);
// 					//要输入的参数
// 					$package = array(
// 							'fileName' => $savename,                                              //文件的绝对路径，包含文件名
// // 							'fileSha'=>sha1($content),
// // 							'fileSize'=>filesize($savename),
// // 							'fileType'=>$fileEx,
// // 							'offset'=>'0',
// 							'dataSize' => 5242880,                                          //分片大小，建议使用默认值5MB
// 							'isTranscode' => 1,                                                  //是否转码
// 							'isScreenshot' => 1,                                                 //是否截图
// 							'isWatermark' => 0,                                                  //是否添加水印
// 							'notifyUrl' =>$_SERVER['SERVER_NAME'].'/'.C("resource_notify_url")
// 					);

					vendor("QcloudApi.Module.VodUpload");
					ob_start();
					$vod = new \VodApi();
					$vod->Init(C("API_SecretId"), C("API_SecretKey"), \VodApi::USAGE_UPLOAD, "gz");
					
					$vod->SetConcurrentNum(10);	//设置并发上传的分片数目，不调用此函数时默认并发上传数为6
					$vod->SetRetryTimes(10);	//设置每个分片可重传的次数，不调用此函数时默认值为5
					
					// $package: 上传的文件配置参数
					$package = array(
							'fileName' => $savename,				//文件的绝对路径，包含文件名
							'dataSize' => 1024*1024,					//分片大小，单位Bytes。断点续传时，dataSize强制使用第一次上传时的值。
							'isTranscode' => 1,					//是否转码
							'isScreenshot' => 1,				//是否截图
							'isWatermark' => 1,					//是否添加水印
							//'notifyUrl' =>$_SERVER['SERVER_NAME'].'/'.C("resource_notify_url")     //已经不再生效
					);
					$vod->UploadVideo($package);
					//$a = $service->MultipartUploadVodFile($package);
					//删除本地文件
					unlink($savename);
					if($vod->getFileId() == '-1'){
						return false;
					}else{
						$fileId = $vod->getFileId();
						$data['file_id'] = $fileId;
						$data['status'] = '1';
						$data['type'] = '2';
						$data['file_name'] = iconv('GB2312', 'UTF-8', $fileName);
						$data['create_time'] = date('Y-m-d H:i:s',time());
						$data['operation_id'] = $_SESSION['ADMIN_ID'];
						$resource_model->add($data);

						ob_end_clean();
						echo '2~'.iconv('GB2312', 'UTF-8', $fileName);exit;
						//return $fileId;
					}
			}else{
				
			}
			return true;
			//echo $totalSize."~".iconv('GB2312', 'UTF-8', $fileName);exit;
		}
	}
	
	
	function getChunkFilename ($chunkNumber, $identifier,$filename){
		global $uploads_dir;
		$temp_dir = $uploads_dir.'/'.$identifier;
		return  $temp_dir.'/'.$filename.'.part'.$chunkNumber;
	}
	
	
	function changeTimeType($seconds) {
		if ($seconds > 3600) {
			$hours = intval($seconds / 3600);
			$minutes = $seconds % 3600;
			$time = $hours . ":" . gmstrftime('%M:%S', $minutes);
		} else {
			$time = gmstrftime('%H:%M:%S', $seconds);
		}
		return $time;
	}
	

}